package state

import (
	"context"
	daqapp "daqctl/internal/app"
	"daqctl/internal/config"
	"fmt"

	"github.com/go-redis/redis/v8"
	logr "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

func PrintAppState(cmd *cobra.Command, args []string) {
	appTypeName, err := cmd.Flags().GetString(daqapp.AppType)
	cobra.CheckErr(err)
	appTypeName = daqapp.MatchAppType(appTypeName)

	tb, err := daqapp.NewAppStateTable()
	cobra.CheckErr(err)

	switch appTypeName {
	case daqapp.AllType:
		apps := daqapp.Apps()
		err := GetAppState(config.DaqCtlConfig.Partition, apps, config.RedisCli)
		appStateMap := daqapp.Apps2Maps(apps)
		if err != nil {
			logr.Error(err)
		} else {
			tb.AddRows(appStateMap)
		}
	case daqapp.ROSType:
		apps := daqapp.ROSApps()
		err := GetAppState(config.DaqCtlConfig.Partition, apps, config.RedisCli)
		appStateMap := daqapp.Apps2Maps(apps)
		if err != nil {
			logr.Error(err)
		} else {
			tb.AddRows(appStateMap)
		}
	case daqapp.BuilderType:
		apps := daqapp.BuilderApps()
		err := GetAppState(config.DaqCtlConfig.Partition, apps, config.RedisCli)
		appStateMap := daqapp.Apps2Maps(apps)
		if err != nil {
			logr.Error(err)
		} else {
			tb.AddRows(appStateMap)
		}
	case daqapp.PSType:
		apps := daqapp.PSApps()
		err := GetAppState(config.DaqCtlConfig.Partition, apps, config.RedisCli)
		appStateMap := daqapp.Apps2Maps(apps)
		if err != nil {
			logr.Error(err)
		} else {
			tb.AddRows(appStateMap)
		}
	case daqapp.ESType:
		apps := daqapp.ESApps()
		err := GetAppState(config.DaqCtlConfig.Partition, apps, config.RedisCli)
		appStateMap := daqapp.Apps2Maps(apps)
		if err != nil {
			logr.Error(err)
		} else {
			tb.AddRows(appStateMap)
		}
	case daqapp.DFMType:
		apps := daqapp.DFMApps()
		err := GetAppState(config.DaqCtlConfig.Partition, apps, config.RedisCli)
		appStateMap := daqapp.Apps2Maps(apps)
		if err != nil {
			logr.Error(err)
		} else {
			tb.AddRows(appStateMap)
		}
	default:
		logr.Errorf("There is no app of type: %s", appTypeName)
	}

	if !tb.Empty() {
		tb.PrintTable()
	} else {
		fmt.Println("No Apps!")
	}
}

// GetAppState 获得app状态
func GetAppState(partion string, apps []daqapp.App, redisCli *redis.Client) error {
	// 构建app在redis的key
	appNames := []string{}
	for _, app := range apps {
		fullAppName := fmt.Sprintf(config.RedisAppStateKeyPattern, partion, app.Name)
		appNames = append(appNames, fullAppName)
	}
	logr.Debug(appNames)

	ctx := context.Background()
	sc, err := redisCli.MGet(ctx, appNames...).Result()
	if err != nil {
		return err
	}
	logr.Debug(sc)

	for i := 0; i < len(sc); i++ {
		state := sc[i]
		if state == nil {
			apps[i].State = "None"
		} else {
			apps[i].State = (state).(string)
		}
	}

	return nil
}
